var Route=require('./route');
var Layer=require('./layer');
var parseUrl = require('parseurl');

var objectRegExp = /^\[object (\S+)\]$/;
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
var Router=module.exports=function(options){
    var opt=options || {};
    function router(req,res,next){
        router.handle(req,res,next);
    }
    router.stack=[];   
    Object.keys(Router).forEach(function(i){
        router[i]=Router[i];
    }) 
    return router;
}
Router.use=function(fn){
    
    var path = '/';
    var callbacks=Array.prototype.slice.call(arguments,0);
    //console.log('Router use',)
    if (callbacks.length === 0) {
        throw new TypeError('Router.use() requires a middleware function')
    }
    for(var i=0;i<callbacks.length;i++){
        var fn = callbacks[i];
        if (typeof fn !== 'function') {
            throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
        }
        var layer = new Layer(path, {
        }, fn);
        layer.route = undefined;
        this.stack.push(layer);
    }
    return this;
}
//循环处理stack 匹配path
//out 函数是finalhandler 函数
Router.handle=function(req,res,out){
    console.log('2 Router.handle',req.url);
    var stack=this.stack;
    var idx = 0;
    var done=out;
    //var done = restore(out, req, 'baseUrl', 'next', 'params');
    next();
    req.next=next;
    function next(){
        console.log('Router.handle next',idx,stack.length)
        if (idx >= stack.length) {
            
            console.log('Router next done');
            //done();
            setImmediate(done);
            return; 
        }
        var layer;
        var match;
        var route;
        var path=parseUrl(req).pathname;
        while(match!==true && idx<stack.length){
            layer=stack[idx];
            match = layer.match(path);
            route = layer.route;
            console.log('idx',idx,'match',match);
            idx+=1;
            if (match !== true) {
                continue;
            }
            if (!route) {
                continue;
            }
            var method = req.method;
            
        }
        var layerPath = layer.path;
        if (route) {
            req.route = route;
        }
        if (route) {
            console.log('Router.handle route',!!route)
            return layer.handle_request(req, res, next);
        }
        if (layerPath.length !== 0) {
            layer.handle_request(req, res, next);
        }
        
    }
    

}
//实例化Layer Route 添加到stack 并返回route
Router.route=function(path){
    console.log('Router.route',path);
    var route=new Route(path);
    var layer=new Layer(path,{},route.dispatch.bind(route));
    layer.route=route;
    this.stack.push(layer);
    return route;
}
function restore(fn, obj) {
    var props = new Array(arguments.length - 2);
    var vals = new Array(arguments.length - 2);
  
    for (var i = 0; i < props.length; i++) {
      props[i] = arguments[i + 2];
      vals[i] = obj[props[i]];
    }
  
    return function () {
      // restore vals
      for (var i = 0; i < props.length; i++) {
        obj[props[i]] = vals[i];
      }
      return fn.apply(this, arguments);
    };
}
